package meijuli.com.join51.business.serviceprovide;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;
import me.foji.anko.QuickAdapter;
import com.jhx.common.utils.Constants;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.activity.WebViewActivity;
import com.jhx.common.framework.QuickBaseFragment;
import com.jhx.common.model.Event;
import com.jhx.common.model.EventBean;
import meijuli.com.join51.business.model.serviceprovide.OrderData;
import meijuli.com.join51.business.model.serviceprovide.OrderPayData;
import meijuli.com.join51.business.model.serviceprovide.PayInfo;
import meijuli.com.join51.business.model.serviceprovide.PayModeType;
import meijuli.com.join51.business.model.serviceprovide.ServiceProviderPayStatus;
import meijuli.com.join51.business.model.serviceprovide.ServiceShop;
import com.jhx.common.widget.CommonDialog;
import meijuli.com.join51.business.ui.widget.CustomItemDecoration;
import com.jhx.common.utils.DisplayUtil;
import meijuli.com.join51.business.utils.GoInternalAppUtil;
import com.jhx.common.utils.ToastUtil;
import com.jhx.common.utils.UserManager;

/**
 * 申请品牌服务商
 *
 * @author Wizong 2017-05-19 13:09
 */
public class ServiceProvideFragment extends QuickBaseFragment implements Contract.ServiceProviderView {
    public static final String PAY_STATUS = "1";
    private Contract.ServiceProviderPresenter mPresenter;
    private ImageView mLastPaymentView;
    private CommonDialog mConfirmPayDialog;
    private View mLastShopView;

    private List<ServiceShop> mServiceShops = new ArrayList<>();
    private List<PayModeType> mCashPayList = new ArrayList<>();
    private QuickAdapter<ServiceShop> mShopAdapter;
    private QuickAdapter<PayModeType> mPaymentAdapter;
    private Handler mHandler = new Handler();

    private int mPaymentSelectType = -1;
    private String mSelectShopId;
    private boolean mHasOrder = false;
    private OrderPayData mOrderPayData;
    private int mRequestCount = 0;
    RecyclerView recyclerServiceShop;
    EditText editOtherMoney;
    TextView textPaymentTitle;
    RecyclerView recyclerPayment;
    TextView txtConfirm;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showToolbar();
    }

    @Override
    public View bindView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_service_provide, null);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        recyclerServiceShop = view.findViewById(R.id.recycler_service_shop);
        editOtherMoney = view.findViewById(R.id.edit_recharge_other_money);
        textPaymentTitle = view.findViewById(R.id.text_payment_title);
        recyclerPayment = view.findViewById(R.id.recyclerview_payment);
        txtConfirm = view.findViewById(R.id.txt_confirm);
        txtConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onViewClicked();
            }
        });
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mPresenter = new ServiceProvidePresenterImpl(this);

        initView();
        initData();
    }

    private void initView() {
        editOtherMoney.setVisibility(View.GONE);
        mShopAdapter = new QuickAdapter<ServiceShop>(getActivity(), R.layout.item_service_shop, mServiceShops) {
            @Override
            public void convert(RecyclerView.ViewHolder viewHolder, final ServiceShop serviceShops, int i) {
                final View itemView = viewHolder.itemView;
                TextView tvMoney = (TextView) itemView.findViewById(R.id.text_service_shop_money);
                TextView tvDesc = (TextView) itemView.findViewById(R.id.text_service_shop_desc);
                tvMoney.setText(serviceShops.getPrice() + "元");
                tvDesc.setText(serviceShops.getDescribe());

                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mLastShopView != null) {
                            mLastShopView.setSelected(false);
                        }
                        itemView.setSelected(true);
                        mSelectShopId = serviceShops.getDmId();
                        mLastShopView = itemView;
                        txtConfirm.setEnabled(mPaymentSelectType > 0);
                    }
                });
            }
        };
        mPaymentAdapter = new QuickAdapter<PayModeType>(getActivity(), R.layout.item_service_pay_type, mCashPayList) {
            @Override
            public void convert(RecyclerView.ViewHolder viewHolder, final PayModeType payModeType, final int position) {
                final View itemView = viewHolder.itemView;
                final TextView tvPayType = (TextView) itemView.findViewById(R.id.txt_paytype);
                final ImageView imagePay = (ImageView) itemView.findViewById(R.id.image_service_pay);
                tvPayType.setText(payModeType.getCation());
                Drawable drawable;
                switch (payModeType.getPayType()) {
                    case Constants.PayList.PAYMENT_TYPE_ALIPAY:
                    case Constants.PayList.PAYMENT_TYPE_AL:
                        drawable = getResources().getDrawable(R.drawable.payment_image_alipay);
                        break;
                    case Constants.PayList.PAYMENT_TYPE_WE_CHAT:
                    case Constants.PayList.PAYMENT_TYPE_WX:
                        drawable = getResources().getDrawable(R.drawable.payment_image_wechat);
                        break;
                    case Constants.PayList.PAYMENT_TYPE_QQ_QR:
                        drawable = getResources().getDrawable(R.drawable.payment_image_qq);
                        break;
                    case Constants.PayList.PAYMENT_QUICK_PAY:
                        drawable = getResources().getDrawable(R.drawable.payment_unlon);
                        break;
                    default:
                        drawable = getResources().getDrawable(R.drawable.ic_launcher);
                }
                if (drawable != null) {
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    tvPayType.setCompoundDrawables(drawable, null, null, null);
                }

                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mLastPaymentView != null) {
                            mLastPaymentView.setSelected(false);
                        }
                        imagePay.setSelected(true);
                        mPaymentSelectType = payModeType.getPayType();
                        mLastPaymentView = imagePay;
                        txtConfirm.setEnabled(!TextUtils.isEmpty(mSelectShopId));
                    }
                });
            }
        };
        recyclerPayment.setAdapter(mPaymentAdapter);
        recyclerPayment.addItemDecoration(new CustomItemDecoration(DisplayUtil.dip2px(getActivity(), 1f),
                LinearLayoutManager.HORIZONTAL));
        recyclerPayment.setLayoutManager(new LinearLayoutManager(getActivity()));

        recyclerServiceShop.setAdapter(mShopAdapter);
        recyclerServiceShop.addItemDecoration(new CustomItemDecoration(DisplayUtil.dip2px(getActivity(), 1f),
                LinearLayoutManager.HORIZONTAL));
        recyclerServiceShop.setLayoutManager(new GridLayoutManager(getActivity(), 3));
    }

    private void initData() {
        showLoadingDialog();
        mPresenter.getServiceShopList();
        mPresenter.getPayList();
    }

    public void onViewClicked() {
        if (TextUtils.isEmpty(mSelectShopId)) {
            ToastUtil.getInstance().showToast(getActivity(), "请选择预购金额");
            return;
        }
        if (mPaymentSelectType < 0) {
            ToastUtil.getInstance().showToast(getActivity(), "请选择支付方式");
            return;
        }
        String phone = UserManager.get().getUser().getPhone();
        if (phone != null) {
            showLoadingDialog();
            mPresenter.serviceShopSubOrder(mSelectShopId, phone);
        } else {
            ToastUtil.getInstance().showToast(getActivity(), "获取联盟商家号码失败");
        }
    }

    @Override
    public void payList(PayInfo payInfo) {
        hideLoadingDialog();
        if(payInfo == null) {
            return;
        }
        mCashPayList = payInfo.getCashPay();
        mPaymentAdapter.setData(mCashPayList);
        recyclerPayment.setAdapter(mPaymentAdapter);
    }

    @Override
    public void serviceShopList(List<ServiceShop> serviceShops) {
        hideLoadingDialog();
        if (serviceShops != null && serviceShops.size() > 0) {
            this.mServiceShops = serviceShops;
            mShopAdapter.setData(serviceShops);
            recyclerServiceShop.setAdapter(mShopAdapter);
        }
    }

    @Override
    public void serviceShopOrder(OrderData orderData) {
        if (orderData != null) {
            showLoadingDialog();
            mPresenter.getOrderPay(orderData.getOrderId(), mPaymentSelectType + "");
        }
    }

    @Override
    public void orderPay(OrderPayData orderPayData) {
        hideLoadingDialog();
        this.mOrderPayData = orderPayData;
        mHasOrder = true;
        if (orderPayData != null) {
            switch (mPaymentSelectType) {
                case Constants.PayList.PAYMENT_TYPE_AL:
                    GoInternalAppUtil.toBrowser(getActivity(), orderPayData.getCodeUrl());
                    break;
                case Constants.PayList.PAYMENT_QUICK_PAY:
                    Intent intent = new Intent(getActivity(), WebViewActivity.class);
                    intent.putExtra(WebViewActivity.KEY_URL, orderPayData.getCodeUrl());
                    intent.putExtra(WebViewActivity.KEY_SELECT, mPaymentSelectType);
                    getActivity().startActivity(intent);
                    break;
                default:
                    ToastUtil.getInstance().showToast(getActivity(), "未支持此支付");
                    break;
            }
        }
    }

    @Override
    public void serviceProviderPayStatus(ServiceProviderPayStatus status) {
        hideLoadingDialog();
        if (status != null && status.getPayStatus() != null && status.getPayStatus().equals(PAY_STATUS)) {
            ToastUtil.getInstance().showToast(getActivity(), "支付成功");
            EventBus.getDefault().post(new EventBean(EventBean.STATUS_SERVICE_PROVIDER_PAY));
            getActivity().finish();
        } else {
            ToastUtil.getInstance().showToast(getActivity(), "支付失败");
        }
    }

    private void showPayDialog() {
        if (mConfirmPayDialog == null) {
            mConfirmPayDialog = new CommonDialog(getActivity());
        }
        mConfirmPayDialog.setTitle("您是否已支付？");
        mConfirmPayDialog.setCancelBtn("未支付");
        mConfirmPayDialog.setConfirmBtn("已支付");
        mConfirmPayDialog.setOnClickListener(new CommonDialog.OnClickListener() {
            @Override
            public void onConfirmClick(View view) {
                showLoadingDialog();
                mHandler.post(new RechargeRunnable());
            }

            @Override
            public void onCancelClick(View view) {
                mConfirmPayDialog.dismiss();
            }
        });
        mConfirmPayDialog.show();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mHasOrder && mOrderPayData != null) {
            mHasOrder = false;
            showPayDialog();
        }
    }

    @Subscribe
    public void event(Event event) {
        if (event != null && event.getCode() == WebViewActivity.CODE_CLOSE) {
            hideLoadingDialog();
            showPayDialog();
        }
    }

    @Override
    public void error(String msg) {
        hideLoadingDialog();
        ToastUtil.getInstance().showToast(getActivity(), msg);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    private class RechargeRunnable implements Runnable {

        @Override
        public void run() {
            mPresenter.checkRecharge(mOrderPayData.getOutTradeNo() == null ? "" : mOrderPayData.getOutTradeNo());
            mHandler.removeCallbacksAndMessages(null);
        }
    }
}
